package com.example.casper.Experiment2024.Activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.casper.Experiment2024.Database.AppDatabase;
import com.example.casper.Experiment2024.Database.PunchRecord;
import com.example.casper.Experiment2024.R;
import com.tencent.tencentmap.mapsdk.maps.model.LatLng;

import java.io.IOException;
import java.util.List;
import android.location.Geocoder;
import android.location.Address;

public class AddClockInActivity extends AppCompatActivity {
    private static final int PICK_IMAGE_REQUEST = 1; // 图片选择请求码
    private EditText descriptionInput;
    private ImageView selectedImageView; // 用于显示选中的照片
    private Bitmap selectedImage;
    private LatLng currentLocation;
    private TextView locationInfoText; // 用于显示位置信息
    private int clockInCount = 0; // 打卡次数

    @SuppressLint({"WrongViewCast", "MissingInflatedId"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_clock_in); // 创建对应的布局文件

        descriptionInput = findViewById(R.id.description_input);
        selectedImageView = findViewById(R.id.selected_image_view); // 绑定 ImageView
        locationInfoText = findViewById(R.id.location_info_text); // 绑定 TextView

        Button addImageButton = findViewById(R.id.add_image_button);
        addImageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openImageChooser();
            }
        });

        Button getLocationButton = findViewById(R.id.get_location_button);
        getLocationButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getCurrentLocation();
            }
        });

        Button saveButton = findViewById(R.id.save_button);
        saveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveClockIn();
            }
        });
    }

    private void openImageChooser() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "选择图片"), PICK_IMAGE_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
            Uri imageUri = data.getData();
            try {
                selectedImage = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
                selectedImageView.setImageBitmap(selectedImage); // 显示选中的照片
                Toast.makeText(this, "图片已选择", Toast.LENGTH_SHORT).show();
            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(this, "图片选择失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void getCurrentLocation() {
        // TODO: 使用腾讯地图API获取当前经纬度
        currentLocation = new LatLng(22.255453, 113.54145); // 示例坐标
        locationInfoText.setText("当前定位: " + currentLocation.latitude + ", " + currentLocation.longitude); // 显示位置信息
        Toast.makeText(this, "当前定位已获取: " + currentLocation.latitude + ", " + currentLocation.longitude, Toast.LENGTH_SHORT).show();
    }

    private void saveClockIn() {
        String description = descriptionInput.getText().toString();

        // 允许用户只输入描述和经纬度
        if (description.isEmpty() || currentLocation == null) {
            Toast.makeText(this, "请填写描述并获取定位", Toast.LENGTH_SHORT).show();
            return;
        }

        // 获取城市名
        String city = getCityFromLocation(currentLocation);

        // 创建打卡记录
        PunchRecord record = new PunchRecord();
        record.setLatitude(currentLocation.latitude);
        record.setLongitude(currentLocation.longitude);
        record.setCity(city);
        record.setDescription(description);

        // 如果用户选择了图片，则保存图片路径
        if (selectedImage != null) {
            record.setPhotoPath("选择的照片路径"); // 这里需要处理照片的实际存储路径
        } else {
            record.setPhotoPath(null); // 如果没有选择图片，设置为null
        }

        record.setTimestamp(System.currentTimeMillis());

        // 保存到数据库
        AppDatabase db = AppDatabase.getInstance(this);
        db.punchRecordDao().insert(record);

        // 更新打卡编号和时间
        clockInCount++;
        Toast.makeText(this, "打卡信息已保存", Toast.LENGTH_SHORT).show();
    }

    private String getCityFromLocation(LatLng latLng) {
        Geocoder geocoder = new Geocoder(this);
        try {
            List<Address> addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
            if (addresses != null && !addresses.isEmpty()) {
                return addresses.get(0).getLocality(); // 获取城市名
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "未知城市";
    }
}